
import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { requestInterceptor, requestInterceptorCatch } from './interceptors/request_interceptor'
import { responseInterceptor } from './interceptors/response_interceptor'

type Result<T> = {
    code: number,
    msg: string,
    data: T
}

class Request {
    // axios 实例
    instance: AxiosInstance

    // 基础配置，url和超时时间
    baseConfig: AxiosRequestConfig = { baseURL: "/api", timeout: 60000 }

    constructor(config: AxiosRequestConfig) {
        // 使用axios.create创建axios实例，配置为基础配置和我们传递进来的配置
        this.instance = axios.create(Object.assign(this.baseConfig, config))

        this.instance.interceptors.request.use(
            requestInterceptor,
            requestInterceptorCatch,
        )
        this.instance.interceptors.response.use(
            responseInterceptor,
        )
    }


    // 定义请求方法
    public request(config: AxiosRequestConfig): Promise<AxiosResponse> {
        return this.instance.request(config);
    }

    public get<T = any>(
        url: string,
        config?: AxiosRequestConfig
    ): Promise<AxiosResponse<Result<T>>> {
        return this.instance.get(url, config);
    }

    public post<T = any>(
        url: string,
        data?: any,
        config?: AxiosRequestConfig
    ): Promise<Result<T>> {
        return this.instance.post(url, data, config);
    }

    public put<T = any>(
        url: string,
        data?: any,
        config?: AxiosRequestConfig
    ): Promise<AxiosResponse<Result<T>>> {
        return this.instance.put(url, data, config);
    }

    public delete<T = any>(
        url: string,
        config?: AxiosRequestConfig
    ): Promise<AxiosResponse<Result<T>>> {
        return this.instance.delete(url, config);
    }



}

// 导出Request，可以用来自定义传递配置来创建实例
// export const Request

// 默认导出Request实例
export default Request